<template>
  <div class="app-container">
    <el-drawer
        v-model="isShow"
        size="50%"
        :destroy-on-close="true"
        @close="closeHandle"
        :close-on-press-escape="false"
        :close-on-click-modal="false"
        :show-close="false"
    >
      <template #header="{ close, titleId, titleClass }">
          <h4 :id="titleId" :class="titleClass">巡查记录</h4>
      </template>
      <el-image
      v-if="imgurl != ''"
        style="width: 100px; height: 100px;border:1px solid #dcdfe6"
        :src="imgurl"
        :previewSrcList="srcList" />
      <el-form :model="form"  ref="formRef" :rules="rules">
        <el-row :gutter="20">
            <el-col :span="24" class="tittle">
                <el-form-item label="巡查信息" label-width="100px" label-position="top" required prop="xcDetailList">
                  <el-checkbox-group v-model="form.xcDetailList" :disabled="isreadonly">
                    <el-row :gutter="20"> <!-- 设置列间距 -->
                      <el-col :span="8" v-for="(item, index) in checkboxOptions" :key="item.xcContentId">
                        <el-checkbox :label="item.name" 
                        :value="{xcContentId:item.xcContentId,name:item.name}" />
                      </el-col>
                    </el-row>
                  </el-checkbox-group>
                </el-form-item>
            </el-col>
            <el-col :span="24" class="tittle" v-if="isOtherSelected">
                <el-form-item label="勾选其他时填写" label-width="100px" label-position="top" required>
                    <el-input v-model="other" type="textarea" resize="none" :rows="3" :readonly="isreadonly" />
                </el-form-item>
            </el-col>
            <el-col :span="24" class="tittle">
                <el-form-item label="具体描述" label-width="100px" label-position="top" >
                    <el-input v-model="info" type="textarea" resize="none" :rows="3" :readonly="isreadonly" />
                </el-form-item>
            </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="submit">提交</el-button>
        <el-button @click="closedrawer" style="margin-left:20px">关闭</el-button>
      </template>
    </el-drawer>
    <el-row :gutter="20" style="height:calc(100% - 40px);">
      <el-col :span="4" style="height: 500px; overflow-y:auto;">
        <div class="head-container">
          <el-tree-select
            v-model="selectedUnitId"
            :data="UnitOptions"
            default-expand-all
            :props="{ value: 'id', label: 'label', children: 'children' }"
            value-key="id"
            placeholder="选择单位"
            check-strictly
            @node-click="handleNodeClickUnit"
        />
        </div>
        <el-divider />
        <div class="head-container" v-loading="loadingdeptOptions">
            <el-tree :data="deptOptions" 
            :props="{ value: 'id', label: 'label', children: 'children' }"
            :expand-on-click-node="false" 
            :filter-node-method="filterNode" 
            ref="deptTreeRef" node-key="id"
            highlight-current
            @node-click="handleNodeClick" />
        </div>
    </el-col>
    <el-col :span="17">
      <el-row :gutter="1"  style="height:100%">
        <el-col :span="colspan0" style="height:50%;margin-bottom: 1px;position:relative" @click="PlayClick(0)" @dblclick="fullscreen(0)">
          <!-- <el-icon @click="fullscreen(0)">1<FullScreen /></el-icon> -->
          <div id="Player0" :style="getPlayerStyle(0)"></div>
        </el-col>
        <el-col :span="colspan1" style="height:50%;margin-bottom: 1px;position:relative" @click="PlayClick(1)" @dblclick="fullscreen(1)">
          <!-- <el-icon @click="fullscreen(1)">2<FullScreen /></el-icon> -->
          <div id="Player1" :style="getPlayerStyle(1)"></div>
        </el-col>
        <el-col :span="colspan2" style="height:50%;position:relative" @click="PlayClick(2)" @dblclick="fullscreen(2)">
          <!-- <el-icon @click="fullscreen(2)">3<FullScreen /></el-icon> -->
          <div id="Player2" :style="getPlayerStyle(2)"></div>
        </el-col>
        <el-col :span="colspan3" style="height:50%;position:relative" @click="PlayClick(3)" @dblclick="fullscreen(3)">
          <!-- <el-icon @click="fullscreen(3)">4<FullScreen /></el-icon> -->
          <div id="Player3" :style="getPlayerStyle(3)"></div>
        </el-col>
      </el-row>
    </el-col>
    <el-col :span="3" style="display: flex;display: -webkit-flex;flex-direction: column;">
      <el-button @click="closevideo" class="mb-4">关闭监控</el-button>
      <el-button @click="savesnapshot" class="mb-4">巡查记录</el-button>
    </el-col>
  </el-row>
  
  </div>
</template>
<script>
// import { getCurrentInstance } from "vue";
// const { proxy } = getCurrentInstance();
 import { ElMessage } from 'element-plus'
 import { getunitDeviceChannelTree } from "@/api/ParameterSetting/Device";
 import { getChannelUrl ,ContentList,} from "@/api/videoApi/videoApi";
 import { MAINAdd ,} from "@/api/monitors/monitors";
 import {deptTreeSelectPost} from "@/api/system/user.js";
export default {
  data() {
    return {
      isShow:false,
      form:{
        bxcunitId:null,
      },
      other: '', // 存储“其他”选项的输入内容
      info:'',
      isreadonly:false,
      playIndex:0,
      loading:false,
      loadingdeptOptions:false,
      activePlayer:0,
      player0: '',
      player1: '',
      player2: '',
      player3: '',
      selectedUnitId:'',
      UnitOptions:[],
      deptOptions:[],
      deptName:'',
      checkboxOptions:[],
      urlList:[],
      imgurl:'',
      srcList:[],
      rules:{
        xcDetailList: [
          { required: true, message: '请选择巡查信息', trigger: 'blur' } // 校验 name 不能为空
        ],
      },
      colspan0:12,
      colspan1:12,
      colspan2:12,
      colspan3:12,
      fullscreenswitch:false,
    }
  },
  created(){
    
  },
  mounted() {
    // 实例化播放器
    this.player0 = new WasmPlayer(null, 'Player0',)
    this.player1 = new WasmPlayer(null, 'Player1', )
    this.player2 = new WasmPlayer(null, 'Player2', )
    this.player3 = new WasmPlayer(null, 'Player3', )
    
    this.getDeptTree()
  },
  computed: {
    // 判断 "其他" 选项是否被选中
    isOtherSelected() {
    return Array.isArray(this.form.xcDetailList) && 
           this.form.xcDetailList.some(item => item.name === "其他");
    }
  },
  methods: {
    /** 查询部门下拉树结构 */
    getDeptTree() {
      this.loading = true
      deptTreeSelectPost({isUnit: true}).then(res => {
        this.UnitOptions  = res.data
        this.loading = false
      });
    },
    callbackfun(e) {
      // console.log(1111)
    },
    // 关闭 抽屉
    closedrawer() {
      this.isShow = false
    },
    // 提交
    submit() {
      this.$refs["formRef"].validate(valid => {
        if (valid) {
          const hasOther = this.form.xcDetailList.some(item => item.name === '其他');
          if(hasOther && !this.other){
            ElMessage.error("巡查问题中选择了'其他'，'勾选其他时填写'内容不能为空 ");
          }else{
            let submitDetailList = this.form.xcDetailList.map(item => {
            if (item.name === '其他') {
              return {
                ...item,
                other: this.other // 假设 this.other 是你要添加的属性值
              };
            }
            return item;
          });
          // 遍历数组，添加 info 属性并删除 name 属性
          submitDetailList.forEach(obj => {
              obj.info = this.info;
              delete obj.name;
          });

          const submitdata = {
            ...this.form,
            res:'1',
            
            xcDetailList:submitDetailList
          }
          MAINAdd(submitdata).then(res => {
            console.log(res)
            this.other = ''
            this.info = ''
            this.isShow = false
          })
          }
          
         }
      })
    },
    closeHandle() {
      this.other = ''
      this.info = ''
      console.log("关闭了")
    },
    playvideo(VideoQuery) {
      switch (this.playIndex) {
        case 0:
          this.player0.stop()
          this.player0.play(this.urlList[0], 1);
          this.player0.VideoQueryV = {}
          this.player0.VideoQueryV = VideoQuery
          console.log(this.player0.VideoQueryV)
          setInterval(() => {
            this.player0.stop()
            this.player0.play(this.urlList[0], 1)
            console.log(this.player0.VideoQueryV)
          }, 60000);
          this.playIndex = 1
          this.activePlayer = 1
          break;
        case 1:
          this.player1.stop()
          this.player1.play(this.urlList[1], 1);
          this.player1.VideoQueryV = {}
          this.player1.VideoQueryV = VideoQuery
          setInterval(() => {
            this.player1.stop()
            this.player1.play(this.urlList[1], 1)
            console.log(this.player1.VideoQueryV)
          }, 60000);
          this.playIndex = 2
          this.activePlayer = 2
          break;
        case 2:
          this.player2.stop()
          this.player2.play(this.urlList[2], 1);
          this.player2.VideoQueryV = {}
          this.player2.VideoQueryV = VideoQuery
          setInterval(() => {
            this.player2.stop()
            this.player2.play(this.urlList[2], 1)
            console.log(this.player2.VideoQueryV)
          }, 60000);
          this.playIndex = 3
          this.activePlayer = 3
          break;
        case 3:
          this.player3.stop()
          this.player3.play(this.urlList[3], 1);
          this.player3.VideoQueryV = {}
          this.player3.VideoQueryV = VideoQuery
          setInterval(() => {
            this.player3.stop()
            this.player3.play(this.urlList[3], 1)
            console.log(this.player3.VideoQueryV)
          }, 60000);
          this.playIndex = 0
          this.activePlayer = 0
          break;
        default:
          ElMessage.error('播放器索引无效');
      }
    }
,
    closevideo() {
      switch (this.playIndex) {
        case 0:
          this.player0.destroy()
          this.player0.url = ''
          this.urlList[this.playIndex] = ''
          this.player0 = new WasmPlayer(null, 'Player0', )
          break;
        case 1:
          this.player1.destroy()
          this.player1.url = ''
          this.urlList[this.playIndex] = ''
          this.player1 = new WasmPlayer(null, 'Player1', )
          break;
        case 2:
          this.player2.destroy()
          this.player2.url = ''
          this.urlList[this.playIndex] = ''
          this.player2 = new WasmPlayer(null, 'Player2', )
          break;
        case 3:
          this.player3.destroy()
          this.player3.url = ''
          this.urlList[this.playIndex] = ''
          this.player3 = new WasmPlayer(null, 'Player3', )
          break;
        default:
          ElMessage.error('播放器索引无效');
      }
    },
    PlayClick(index){
      switch (index) {
        case 0:
          this.form =  this.player0.VideoQueryV ? this.player0.VideoQueryV : this.form
          break;
        case 1:
        this.form =  this.player1.VideoQueryV ? this.player1.VideoQueryV : this.form
          break;
        case 2:
        this.form =  this.player2.VideoQueryV ? this.player2.VideoQueryV : this.form
          break;
        case 3:
        this.form =  this.player3.VideoQueryV ? this.player3.VideoQueryV : this.form
          break;
        default:
          ElMessage.error('播放器索引无效');
      }
      this.playIndex = index
      this.activePlayer = index;
    },
    PlayDoubleClick(index){
      switch (index) {
        case 0:
          this.player0.fullScreen()
          break;
        case 1:
          this.player1.fullScreen()
          break;
        case 2:
          this.player2.fullScreen()
          break;
        case 3:
          this.player3.fullScreen()
          break;
        default:
          ElMessage.error('播放器索引无效');
      }
      this.playIndex = index
      this.activePlayer = index;
    },
    
    getPlayerStyle(index) {
      // 如果当前播放器是选中的播放器，返回带边框的样式，否则返回空样式
      return this.activePlayer == index
        ? { border: '2px solid red' } // 选中的播放器添加红色边框
        : {};
    },
    filterNode(value, data){
      if (!value) return true;
      return data.deptName.indexOf(value) !== -1;
    },
    handleNodeClickUnit(data){
      this.form = this.form || {};
      this.form.bxcunitId = data.id
      this.getunitDeviceChannelTreeList(data.id)
    },

    handleNodeClick(data) {
      // 处理节点单击事件
        if(data.channelcode){
          const playerQuery = {
            deviceId:data.channelcode,
            channel:data.channels,
            monitorServerId:data.monitorserverId,
          }
        const VideoQuery = {
          bxcunitId:this.form.bxcunitId ? this.form.bxcunitId : '',
          xcplace:data.channelname,
          xcroomId:data.channelcode,
          xctype:'1',
        }
        this.form.xcDetailList = []
        this.form.xcpic = ''
        this.form = {
          ...this.form,
          res:"0",
          xctype:'1',
          xcroomId:data.channelcode,
          xcplace:data.channelname,
        } 
        MAINAdd(this.form).then(res => {
          })
        getChannelUrl(playerQuery).then(res => {
            var mergeUrl = res.data.prefix + res.data.EasyDarwin.Body.URL
            this.urlList[this.playIndex] = mergeUrl
            this.playvideo(VideoQuery)
        })
      }
      
    },

    getunitDeviceChannelTreeList(UnitId) {
      this.loadingdeptOptions = true
      this.deptOptions = []
      getunitDeviceChannelTree(UnitId).then(res => {
        // 递归转换 roomTypes 中的结构
        const transformRoomTypes = (roomTypes) => {
          return roomTypes.map(room => {
            // 保留原有的 id 和 label，如果存在的话
            const transformedRoom = {
              ...room,
              label: room.label || room.roomname,  // 仅当 label 不存在时才使用 roomname
              id: room.id || room.roomId          // 仅当 id 不存在时才使用 roomId
            };

            if (room.baseMonitorChannels) {
              // 将 baseMonitorChannels 改为 children，并处理其中的字段
              transformedRoom.children = room.baseMonitorChannels.map(channel => {
                return {
                  ...channel,
                  label: channel.label || channel.channelname, // 仅当 label 不存在时才使用 channelname
                  id: channel.id || channel.channelcode       // 仅当 id 不存在时才使用 channelcode
                };
              });
              delete transformedRoom.baseMonitorChannels; // 删除 baseMonitorChannels 字段
            }
            // 递归处理嵌套的 children（即 room 下的子房间）
            if (room.children && room.children.length > 0) {
              transformedRoom.children = transformRoomTypes(room.children);
            }
            return transformedRoom;
          });
        };
        if (res.data && Array.isArray(res.data) && res.data[0] && res.data[0].roomTypes) {
            var roomTypesdata = transformRoomTypes(res.data[0].roomTypes);
        } else {
            ElMessage.error('当前单位无监控节点');
            this.loadingdeptOptions = false
        }
        // var roomTypesdata = transformRoomTypes(res.data[0].roomTypes);
        // 处理 videoTypes
        if (res.data && res.data[0] && res.data[0].videoTypes) {
            let videoTypesdata = res.data[0].videoTypes;
            videoTypesdata.forEach(videoType => {
                videoType.children.forEach(channel => {
                    channel.label = channel.label || channel.channelname; // 使用 channelname 作为备选
                    channel.id = channel.monitorchannelsId || channel.channelcode; // 使用 channelcode 作为备选
                });
            });
            this.deptOptions = [
              ...roomTypesdata,
              ...videoTypesdata
            ];
        } else {
            console.error("videoTypes data is missing in the response:", res.data);
        }
        this.loadingdeptOptions = false
      });
    },
    fullscreen(index){
      switch (index) {
        case 0:
          if(this.fullscreenswitch){
            this.colspan0 = 12
            this.colspan1 = 12
            this.colspan2 = 12
            this.colspan3 = 12
            this.fullscreenswitch = false
          }else{
            this.colspan0 = 24
            this.colspan1 = 0
            this.colspan2 = 0
            this.colspan3 = 0
            this.fullscreenswitch = true
          }
          break;
        case 1:
          if(this.fullscreenswitch){
              this.colspan0 = 12
              this.colspan1 = 12
              this.colspan2 = 12
              this.colspan3 = 12
              this.fullscreenswitch = false
          }else{
            this.colspan0 = 0
            this.colspan1 = 24
            this.colspan2 = 0
            this.colspan3 = 0
            this.fullscreenswitch = true
          }
          break;
        case 2:
          if(this.fullscreenswitch){
              this.colspan0 = 12
              this.colspan1 = 12
              this.colspan2 = 12
              this.colspan3 = 12
              this.fullscreenswitch = false
          }else{
            this.colspan0 = 0
            this.colspan1 = 0
            this.colspan2 = 24
            this.colspan3 = 0
            this.fullscreenswitch = true
          }
          break;
        case 3:
          if(this.fullscreenswitch){
              this.colspan0 = 12
              this.colspan1 = 12
              this.colspan2 = 12
              this.colspan3 = 12
              this.fullscreenswitch = false
          }else{
            this.colspan0 = 0
            this.colspan1 = 0
            this.colspan2 = 0
            this.colspan3 = 24
            this.fullscreenswitch = true
          }
          break;
        default:
          ElMessage.error('播放器索引无效');
      }
    },
// 快照
    savesnapshot() {
      var videoElement = null
      if(this.playIndex == 0){
        if(this.player0.url){
          videoElement = document.querySelector('#Player0 video'); // 获取视频元素
        }else{
          ElMessage.warning('当前选中窗口无视频播放');
          return
        }
      }
      if(this.playIndex == 1){
        if(this.player1.url){
          videoElement = document.querySelector('#Player1 video'); // 获取视频元素
        }else{
          ElMessage.warning('当前选中窗口无视频播放');
          return
        }
      }
      if(this.playIndex == 2){
        if(this.player2.url){
          videoElement = document.querySelector('#Player2 video'); // 获取视频元素
        }else{
          ElMessage.warning('当前选中窗口无视频播放');
          return
        }
      }
      if(this.playIndex == 3){
        if(this.player3.url){
          videoElement = document.querySelector('#Player3 video'); // 获取视频元素
        }else{
          ElMessage.warning('当前选中窗口无视频播放');
          return
        }
      }
    this.isShow = true
    if (videoElement) {
        const canvas = document.createElement('canvas');
        canvas.width = '400';  // 设置 canvas 尺寸与视频一致
        canvas.height = '280';
        
        const ctx = canvas.getContext('2d');
        ctx.drawImage(videoElement, 0, 0, canvas.width, canvas.height); // 绘制视频到 canvas 上
        // 将 canvas 转换为图片
        const imgData = canvas.toDataURL('image/png');
        this.imgurl = imgData
        
        this.srcList[0] = imgData
        this.form.xcpic = imgData
        
        const paging = {
           // 页码
            pageNum: 1,
            // 分页数量
            pageSize: 10,
            isAsc: 'ascending',
            orderByColumn: 'orders'
        }
        const queryParams = {
        }
        ContentList(queryParams,paging).then(res => {
            const filteredData = res.data.filter(item => item.type === "1" || item.type === "2");
            // 根据 orders 升序排序
            const sortedData = filteredData.sort((a, b) => Number(a.orders) - Number(b.orders));
            this.checkboxOptions = sortedData;
        })
    } else {
        console.error('视频元素未找到');
    }

    },
  }  
}
</script>
<style scoped>
.app-container { height: calc(100vh - 84px);width: 100%; }
.el-button+.el-button{margin-left: 0;}
.player-content{height: 100%;}
/* :deep() .el-icon{position:absolute;top:5px;right:5px;z-index:99999;color:white;font-size:18px;cursor:pointer} */
</style>